import React, { useEffect, useRef, useState } from "react";
import {
  Tabs,
  List,
  Avatar,
  Button,
  ErrorBlock,
  Popup,
  Toast,
  Dialog,
  Input,
  InfiniteScroll,
} from "antd-mobile";
import { FillinOutline, RightOutline } from "antd-mobile-icons";
import {
  addUserToHouse,
  getBsUserList,
  getSysUserList,
  getWaitUserList,
  updateBsUserInfo,
} from "@/services";
import type {
  GetWaitUserListReq,
  WaitUserInfo,
  GetSysUserListReq,
  SysUserItem,
} from "@/services";
import { useUserStore } from "@/store";
import { trim } from "lodash-es";
import { history } from "umi";
import { useGetState, useSafeState } from "ahooks";
import { parseImageUrl } from "@/utils";
const Home: React.FC = () => {
  const [waitUserList, setWaitUserList, gotWaitUserList] = useGetState<
    WaitUserInfo[]
  >([]);
  const listReqParams = useRef<Partial<GetWaitUserListReq>>({
    page: 0,
    size: 10,
  });
  const [popupVisible, setPopupVisible] = useState(false);
  // 组员列表
  const [groupUserList, setGroupUserList] = useState<SysUserItem[]>([]);
  const { userInfo } = useUserStore();
  const curSelectedCustomer = useRef<WaitUserInfo | null>(null);
  const [hasMore, setHasMore] = useSafeState(false);
  const loading = useRef(false);

  const resetData = () => {
    listReqParams.current.page = 1;
    setWaitUserList([]);
  };

  const getWaitUserListRequest = async (refresh?: boolean) => {
    if (!userInfo.onlyId) return;
    const req: GetWaitUserListReq = {
      sysUserId: userInfo.type == 0 ? userInfo.onlyId : "",
      bsUserId: "",
      isContact: -1,
      sysUserIdGroup: userInfo.type == 1 ? userInfo.onlyId : "",
      allocationStatus: -1,
      page: 1,
      size: 10,
      ...listReqParams.current,
    };
    if (loading.current) return;
    loading.current = true;
    const res = await getWaitUserList(req);
    loading.current = false;
    if (res.code === 200) {
      if (refresh) {
        const tempList = res.data.list;
        const hisList = gotWaitUserList();
        const start = hisList.length - tempList.length;
        const newList = [...hisList.slice(0, start), ...tempList];
        setHasMore(newList.length < res.data.total);
        setWaitUserList(newList);
      } else {
        const newList = [...gotWaitUserList(), ...res.data.list];
        setHasMore(newList.length < res.data.total);
        setWaitUserList(newList);
      }
    }
  };

  // 获取组员列表
  const getGroupUserListRequest = async () => {
    const req: GetSysUserListReq = {
      onlyId: "", // 主键
      orgId: "", // 机构ID
      username: "", // 用户名
      password: "", // 密码
      phone: "", // 手机号
      realName: "", // 真实姓名
      roleId: "", // 角色ID
      type: 0, // 员工类型：1、后台
      parentId: userInfo.onlyId, // 组长的用户id
      pageIndex: 1, // 分页页码
      pageSize: 999, // 分页每页数量
    };
    const res = await getSysUserList(req);
    if (res.code === 200) {
      const groupResult = res.data.list || [];
      userInfo.realName = userInfo.realName + "(组长)";
      groupResult.unshift(userInfo);
      setGroupUserList(groupResult);
    }
  };

  useEffect(() => {
    if (userInfo.onlyId) {
      resetData();
      getWaitUserListRequest(true);
    }
  }, [userInfo.onlyId]);

  // 分配员工
  const allocationUserHandle = async (sysUserId: string) => {
    if (!curSelectedCustomer.current?.onlyId) return;
    const res = await addUserToHouse({
      unassignedId: curSelectedCustomer.current?.onlyId, // 分配列表id
      userId: sysUserId,
    });
    if (res.code === 200 && res.data.result) {
      getWaitUserListRequest(true);
      setPopupVisible(false);
      Toast.show({
        icon: "success",
        content: "分配成功！",
      });
    } else {
      Toast.show({
        icon: "fail",
        content: "分配失败！",
      });
    }
  };

  // 更新用户姓名
  const updateBsUserRealNameHandle = async (
    realName: string,
    onlyId: string
  ) => {
    const userListRes = await getBsUserList({
      onlyId,
      nickName: "",
      tel: "",
      openId: "",
      unionId: "",
      infoLevel: -1,
      promoter: "", // 推广人姓名
      promoterUserId: "", // 推广人Id
      type: -1,
      orgId: "", // 组织id
      page: 1,
      size: 10,
    });
    if (userListRes.code != 200 || userListRes.data.list.length == 0) {
      Toast.show({
        icon: "fail",
        content: "更新失败！",
      });
      return;
    }
    const updateUserInfo = userListRes.data.list[0];
    updateUserInfo.realName = realName;
    const res = await updateBsUserInfo(updateUserInfo);
    if (res.code === 200) {
      Toast.show({
        icon: "success",
        content: "更新成功！",
      });
      getWaitUserListRequest(true);
    }
  };

  const loadMore = async (isRetry: boolean) => {
    if (!isRetry) {
      listReqParams.current.page = listReqParams.current.page! + 1;
    }
    await getWaitUserListRequest();
  };

  useEffect(() => {
    if (userInfo.type === 1) {
      getGroupUserListRequest();
    }
  }, [userInfo.type]);

  return (
    <div className="min-h-100vh">
      {userInfo.type === 1 && (
        <Tabs
          defaultActiveKey={listReqParams.current.allocationStatus?.toString()}
          onChange={(key) => {
            listReqParams.current.allocationStatus = Number(key);
            resetData();
            getWaitUserListRequest();
          }}
          activeLineMode="fixed"
        >
          <Tabs.Tab title="全部用户" key={-1}></Tabs.Tab>
          <Tabs.Tab title="未分配" key={0}></Tabs.Tab>
          <Tabs.Tab title="已分配" key={1}></Tabs.Tab>
        </Tabs>
      )}
      <List>
        {waitUserList.map((item) => {
          return (
            <List.Item
              key={item.onlyId}
              prefix={<Avatar src={parseImageUrl(item.bsUserHeadImg)} />}
              description={
                <>
                  <span>{item.bsUserPhone}</span>
                  {item.bsUserName && (
                    <div className="ml-4px text-gray-4 truncate w-90px">
                      {item.bsUserName}
                    </div>
                  )}
                </>
              }
              extra={
                userInfo.type === 1 && (
                  <>
                    {item.sysUserId ? (
                      <>
                        <span className="text-14px mr-10px text-green-6">
                          已分配
                          <RightOutline />
                          {item.sysUserName}
                        </span>
                        <Button
                          color="primary"
                          fill="outline"
                          onClick={(e) => {
                            e.preventDefault();
                            e.stopPropagation();
                            setPopupVisible(true);
                            curSelectedCustomer.current = item;
                          }}
                        >
                          转移
                        </Button>
                      </>
                    ) : (
                      <Button
                        color="primary"
                        fill="outline"
                        onClick={(e) => {
                          e.preventDefault();
                          e.stopPropagation();
                          setPopupVisible(true);
                          curSelectedCustomer.current = item;
                        }}
                      >
                        分配
                      </Button>
                    )}
                  </>
                )
              }
              onClick={(e) => {
                e.preventDefault();
                e.stopPropagation();
                history.push(
                  `/modules/user-visitor?onlyId=${item.onlyId}&userId=${item.bsUserId}`
                );
              }}
            >
              <span
                onClick={async (e) => {
                  e.preventDefault();
                  e.stopPropagation();
                  let realName = item.bsRealName;
                  const result = await Dialog.confirm({
                    title: "填写姓名",
                    content: (
                      <div className="border-b border-gray-1  border-solid h-40px flex items-center px-10px rounded">
                        <Input
                          type="text"
                          defaultValue={realName}
                          placeholder="请输入姓名"
                          onChange={(val) => {
                            realName = trim(val);
                          }}
                        />
                      </div>
                    ),
                  });
                  if (result && realName) {
                    updateBsUserRealNameHandle(realName, item.bsUserId);
                  }
                }}
              >
                <span className="text-blue-6">
                  {item.bsRealName || "未填写姓名"}
                </span>
                <FillinOutline className="text-blue-6 ml-2" />
              </span>
            </List.Item>
          );
        })}
      </List>
      {waitUserList.length === 0 && (
        <div className="mt-100px ">
          <ErrorBlock status="empty" title="暂无数据" description="" />
        </div>
      )}

      <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />

      <Popup
        visible={popupVisible}
        onMaskClick={() => {
          curSelectedCustomer.current = null;
          setPopupVisible(false);
        }}
        position="right"
        bodyStyle={{ width: "60vw" }}
      >
        <List header="我的组员">
          {groupUserList.map((item) => (
            <List.Item
              key={item.onlyId + "sysuser"}
              extra={
                <Button
                  color="primary"
                  fill="none"
                  onClick={async () => {
                    const confirm = await Dialog.confirm({
                      title: "提示",
                      content: `确定分配给${item.realName}?`,
                    });
                    if (confirm) {
                      allocationUserHandle(item.onlyId);
                    }
                  }}
                >
                  选择
                </Button>
              }
            >
              {item.realName}
            </List.Item>
          ))}
        </List>
      </Popup>
    </div>
  );
};

export default Home;
